<?php

require_once 'phpmoko/db/MySQLDataResult.php';

class MySQL
{
	private $link = null;
	private $errors = false;
	private $SQL = false;
	
	function __construct($server, $username, $password, $database_name, $persistent = true)
	{
		if ($persistent)
			$this->link = @mysql_pconnect($server, $username, $password);
		else
			$this->link = @mysql_connect($server, $username, $password);
		
		if (!$this->link)
		{
			echo "Unable to connect to DB: " . mysql_error();
			exit;
		}
		
		@mysql_query("SET CHARACTER SET 'utf8'", $this->link);
		
		if (!mysql_select_db($database_name, $this->link))
		{
			echo "Unable to select mydbname: " . mysql_error();
			exit;
		}
	}
	
	function close()
	{
		@mysql_close($this->link);
	}
	
	function getLink()
	{
		return $this->link;
	}

	function showErrors($showErrors)
	{
		$this->errors = $showErrors;
	}
	
	function showSQL($showSQL)
	{
		$this->SQL = $showSQL;
	}
	
	/**
	 * @param MySQLCommand $mysqlCommand
	 * @return MySQLDataResult unknown_type
	 */
	function query($mysqlCommand)
	{
		$query = $mysqlCommand->generateSQL();

		$result = @mysql_query($query, $this->link);

		if (($this->errors && mysql_error()) || $this->SQL)
		{
			echo $query."<br>";
			echo mysql_error()."<br>";
		}

		if ($result === FALSE)
		{
			echo "<br><b style=\"color:red\">".mysql_error()."<br>".$query."</b>";
			throw new Exception(mysql_error());
		}
		
		return new MySQLDataResult($result);
	}
	
	function insertId()
	{
		return mysql_insert_id();
	}
}
?>